import React from 'react';
import { inject, observer } from 'mobx-react';
import { Button, Tabs,Card,Pagination,Row,Col } from 'antd';
import {WeaRightMenu,WeaTop,WeaTab,WeaErrorPage,WeaAlertPage,WeaTools,WeaLeftRightLayout,WeaProgress,WeaLocaleProvider} from 'ecCom';
import {toJS} from "mobx";
import {Condition,getAdButtons} from '../list/listCondition';
import {WeaTableNew} from 'comsMobx';
const WeaTable = WeaTableNew.WeaTable;
const getLabel = WeaLocaleProvider.getLabel;
import ListLeftTree from '../list/listLeftTree'

@inject('prjMonitorStore')
@observer
class MonitorResult extends React.Component {
    constructor(props) {
        super(props);
    }

    componentDidMount(){
        const { prjMonitorStore } = this.props;
        WeaTools.callApi('/api/proj/pcproject/getPrjMonitorRight', 'GET', {}).then(data=>{
            prjMonitorStore.hasRight = data.isright;
            prjMonitorStore.verified = true;
            if(data.isright){
                this.doInit(this.props);
                //initTreeDatas();
            }
        });
    }
    
    doInit(props){
        const { location:{query},prjMonitorStore } = props;
        const {initTreeDatas,initDatas,} = prjMonitorStore;
        initDatas(query);
        // initTreeDatas();
    }
    componentWillUnmount(){
        const { prjMonitorStore } = this.props;
        prjMonitorStore.clearStatus();
    }  
    render(){
        const {prjMonitorStore} = this.props;
        const {title,loading,tableStore,showSearchAd,form,showLeft,verified,hasRight} = prjMonitorStore;
        const formParams = form.getFormParams() || {};
        if (verified && !hasRight) {
            return (<WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@it4wd0`} >
                    <div style={{color : '#000'}}>
                        {getLabel(2012,"对不起，您暂时没有权限！")}
                    </div>
                </WeaAlertPage>
            )
        } 
        if (verified && hasRight) {
            return (
                <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@zlh37c`} datas={this.getRightMenu()} onClick={this.onRightMenuClick.bind(this)}  >
                    <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@5ptl48`}
                            title={getLabel(19870,"项目监控")}
                            loading={loading}
                            icon={<i className='icon-coms-project' />}
                            iconBgcolor='#217346'
                            buttons={this.getTopButtons()}
                            buttonSpace={10}
                            showDropIcon={true}
                            dropMenuDatas={this.getRightMenu()}
                            onDropMenuClick={this.onRightMenuClick.bind(this)} 
                        >
                        <WeaLeftRightLayout ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@racojw`}
                            isNew = {true}
                            showLeft = {showLeft}
                            leftCom={<ListLeftTree ecId={`${this && this.props && this.props.ecId || ''}_ListLeftTree@hfduzn`} listStore={prjMonitorStore} key={this.props.location.key}  initkey={"all"} />}
                            onCollapse={showLeft => prjMonitorStore.setLeftShow(showLeft)}
                        >
                            <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@aza62t`}
                                buttonsAd={getAdButtons(prjMonitorStore,this.props.ecId || '')}
                                searchType={['base','advanced']}
                                searchsBaseValue={formParams.name}
                                setShowSearchAd={bool=>{prjMonitorStore.setShowSearchAd(bool)}}
                                hideSearchAd={()=> prjMonitorStore.setShowSearchAd(false)}
                                searchsAd={
                                    <div><Condition ecId={`${this && this.props && this.props.ecId || ''}_Condition@qb36yo`} listStore={prjMonitorStore} form={form} onEnterSearch={this.onEnterSearch} ></Condition></div>
                                }
                                showSearchAd={showSearchAd}
                                onSearch={v=>{prjMonitorStore.doSearch()}}
                                onSearchChange={v=>{prjMonitorStore.appendFormFields({name:{value:v}})}}
                                onChange={ this.changeData }
                            />
                                <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@likfqz`} 
                                    comsWeaTableStore={tableStore}
                                    hasOrder={true}
                                    needScroll={true}
                                    getColumns={c=>this.reRenderColumns(c)}
                                    tableWidth={this.tableWidth}
                                    onOperatesClick={this.onOperatesClick.bind(this)}
                                />
                            </WeaLeftRightLayout>
                        </WeaTop>
                </WeaRightMenu>)
        }
       

    }

    getTopButtons(){
        const {prjMonitorStore} = this.props;
        const {rightMenu,tableStore} = prjMonitorStore;
        let {selectedRowKeys} = tableStore;
        let btnArr = [];
        let that = this;
        const isDisabled = !(selectedRowKeys.length>0 && `${toJS(selectedRowKeys)}`);
        rightMenu && rightMenu.length>0 && toJS(rightMenu).map(m=>{
            m.isTop == '1' && btnArr.length < 4 && btnArr.push(
                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@226pai@${m.type}`} type="primary" 
                   disabled={isDisabled && m.isControl == "1"}
                   onClick={()=>{
                       if(m.type == "BTN_DELETEBATCH"){ //导出Excel
                            prjMonitorStore.delPrjInfo({method:"del",prjid:`${toJS(selectedRowKeys)}`})
                        }
                    }}>
                {m.menuName}
               </Button>
           );
       });
       return btnArr;
    }

    getRightMenu(){
        const {prjMonitorStore }= this.props;
        const {rightMenu, tableStore} = prjMonitorStore;
        let {selectedRowKeys} = tableStore;
        const isDisabled = !(selectedRowKeys.length>0 && `${toJS(selectedRowKeys)}`);
        let btnArr = [];
        rightMenu && rightMenu.length>0 && rightMenu.map(m=>{
            btnArr.push({
                icon: <i className={m.menuIcon} />,
                content: m.menuName,
                disabled : isDisabled && m.isControl == "1"
            })
        });
    	return btnArr
    }
    onRightMenuClick(key){
        const {prjMonitorStore }= this.props;
        const {rightMenu,tableStore} = prjMonitorStore;
        let {selectedRowKeys} = tableStore;
        let that = this;
        rightMenu &&  rightMenu.length>0  && rightMenu.map((m,i)=>{
        	if(Number(key) == i){
                let fn = m.menuFun.indexOf('this') >= 0 ? `${m.menuFun.split('this')[0]})` : m.menuFun;
                if(m.type == "BTN_SEARCH"){ //定制列
                    prjMonitorStore.doSearch();
                }else if(m.type == "BTN_COLUMN"){ //定制列
                    prjMonitorStore.onShowColumn();
                }else if(m.type == "BTN_DELETEBATCH"){
                    prjMonitorStore.delPrjInfo({method:"del",prjid:`${toJS(selectedRowKeys)}`});
                }
            }
        });
    }
    reRenderColumns(columns){
        columns.forEach((c,i)=>{
            if(c.dataIndex=='finish'){
                c.render = function(text, record){
                    return  <span  className='wea-prj-progressStyle' >
                    <WeaProgress ecId={`${this && this.props && this.props.ecId || ''}_WeaProgress@n0b3eo@${i}`} percent={record.finish||0}  strokeColor={record.finishspan} />
                </span>
                }
            } else {
              c.render = function(text, record){
                  let valueSpan = record[c.dataIndex + "span"] !== undefined ? record[c.dataIndex + "span"] : record[c.dataIndex];
                  return <span dangerouslySetInnerHTML={{__html: valueSpan}}></span>
                }
            }
        })
        return columns;
    }

    tableWidth = (columns) => {
        let width = 0;
        let cols = 0;
        columns.map(col => {
          if (col.display === 'true') {
            let oldwidth = col.oldWidth || '10%';
            let widthInt = parseFloat(oldwidth.replace('%', ''));
            if (widthInt <= 0) {
              widthInt = 10;
            }
            width += widthInt;
            cols++
          }
        })
        //超过10列，才出现滚动条，width>100才出现滚动条
        if(cols<=10){
            width = 100 ;
        }
        return `${width}%`;
    }

    changeData=(key)=>{
        const {prjMonitorStore} = this.props;
        prjMonitorStore.setShowSearchAd(false);
        prjMonitorStore.doSearch({
            tabkey:key
        });
    }

    onOperatesClick(record,index,operate,flag){
        let that = this;
        const {prjMonitorStore }= this.props;
        let _href = operate && operate.href ? operate.href : "";
        let fn = _href.replace("javascript:","");
		fn = fn.substring(0,fn.indexOf('('));
        if(fn != ""){
           if("onDel"==fn){
                prjMonitorStore.delPrjInfo({method:"del",prjid:record.randomFieldId});
           }
       }
   }

   onEnterSearch=() =>{
        const {prjMonitorStore }= this.props;
        prjMonitorStore.doSearch();
        prjMonitorStore.setShowSearchAd(false);
	}

}

export default WeaTools.tryCatch(React,
    props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@hnbzwn`} msg={ props.error ? props.error : getLabel(383324,"对不起，该页面异常，请联系管理员")} />,
    {error: ""}
)(MonitorResult);